package pw.hais.view;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.util.Map;

import pw.hais.utils.L;
import pw.hais.utils.R;

/**
 * 超级View
 * 1、描边功能   stroke_size、stroke_color
 * 2、加载字体   font_path
 * 3、数字动态变化 setNumAutoAnim(int time,int inNum,int toNum)
 * 4、图片代替文本 image_size_is_auto、setImageText(Map<String, Drawable> drawableMap, String str)
 */
public class TextSuperView extends TextView {

    public TextSuperView(Context context) {
        super(context);
        init(context, null, 0);
    }

    public TextSuperView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public TextSuperView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private String font_path;   //字体路径
    private int stroke_size;    //描边大小
    private int stroke_color;   //描边颜色
    private boolean image_size_is_auto;   //大小是否自适应

    private void init(Context context, AttributeSet attrs, int defStyle) {
        //获取参数
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TextView);
        font_path = array.getString(R.styleable.TextView_font_path);
        stroke_size = array.getDimensionPixelSize(R.styleable.TextView_stroke_size, 0);
        stroke_color = array.getColor(R.styleable.TextView_stroke_color, 0x00ffffff);
        image_size_is_auto = array.getBoolean(R.styleable.TextView_image_size_is_auto, true);
        //字体
        if (font_path != null) {
            try {
                Typeface iconfont = Typeface.createFromAsset(context.getAssets(), font_path);
                setTypeface(iconfont);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (stroke_size != 0) {
            // 描外层
            //super.setTextColor(Color.BLUE); // 不能直接这么设，如此会导致递归
            setTextColorUseReflection(stroke_color);
            getPaint().setStrokeWidth(stroke_size);  // 描边宽度
            getPaint().setStyle(Style.FILL_AND_STROKE); //描边种类
            getPaint().setFakeBoldText(true); // 外层text采用粗体
            getPaint().setShadowLayer(1, 0, 0, 0); //字体的阴影效果，可以忽略
            super.onDraw(canvas);

            // 描内层，恢复原先的画笔
            setTextColorUseReflection(getTextColors().getDefaultColor());
            getPaint().setStrokeWidth(0);
            getPaint().setStyle(Style.FILL_AND_STROKE);
            getPaint().setFakeBoldText(false);
            getPaint().setShadowLayer(0, 0, 0, 0);
        }
        super.onDraw(canvas);
    }

    /**
     * 获取画笔
     */
    private void setTextColorUseReflection(int color) {
        Field textColorField;
        try {
            textColorField = TextView.class.getDeclaredField("mCurTextColor");
            textColorField.setAccessible(true);
            textColorField.set(this, color);
            textColorField.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        getPaint().setColor(color);
    }


    /**
     * 设置 图片文字
     */
    public void setImageText(Map<String, Drawable> drawableMap, String str) {
        if (drawableMap == null || drawableMap.size() == 0) return;
        //设置为画笔
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(str);
        //给 Drawable 设置宽度,并转为Span
        for (String key : drawableMap.keySet()) {
            Drawable drawable = drawableMap.get(key);
            if (image_size_is_auto) {
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            } else {
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), getHeight());
            }
            //开始循环替换
            int keyCount = count(key, str);
            int xy = -1;    //出现的位置
            for (int i = 0; i < keyCount; i++) {
                xy = str.indexOf(key, xy + 1);  //获取出现的位置
                ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
                spannableStringBuilder.setSpan(span, xy, xy + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
        setText(spannableStringBuilder);
    }

    /**
     * 获取字符串 出现次数
     */
    private static int count(String one, String two) {
        int oneLen = one.length();
        int twoLen = two.length();
        twoLen = twoLen - two.replace(one, "").length();
        return oneLen == 0 ? 0 : (twoLen / oneLen);
    }

    /** 动态增长 */
    public void setNumAutoAnim(int time,int inNum,int toNum, final String title){
        setNumAutoAnim(time, inNum, toNum, new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setText(title+String.valueOf(animation.getAnimatedValue()));
            }
        },null);
    }

    public void setNumAutoAnim(int time, int inNum, int toNum, ValueAnimator.AnimatorUpdateListener updateListener, Animator.AnimatorListener listener){
        ValueAnimator valueAnimator = ValueAnimator.ofInt(inNum,toNum);
        valueAnimator.setDuration(time);
        if(updateListener!=null)valueAnimator.addUpdateListener(updateListener);
        if(listener!=null)valueAnimator.addListener(listener);
        valueAnimator.start();
    }
}